// 商品分销
(function() {

	//构造函数
	var _con = function(goods_id) {
		var self = this;

		var goods = GoodsCon.getAlone(goods_id);

		var bus_id = goods.bus_id;

		if (!goods) {
			throwCusError("找不到指定商品");
		}

		//ID编号
		self._id = db_id_prefix + goods_id + "|" + bus_id;

		//推荐者依赖关系表
		self.user_map = {};

		self.goods_id = goods_id;

		self.bus_id = bus_id;

		db.insert(db_table_name, self);
		console.log("创建了一个商品分销：", self._id);
	};
	//PS:模块的暴露放在require skill前面，因为二者互相依赖
	module.exports = _con;
	//技能
	_con.prototype = require("./skill");
	_con.STATE = {
		"未申请兑换": 0,
		"申请兑换中": 1,
		"商家已付款": 2,
		"用户确认收款": 0 //==未申请兑换
	};
	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
		}
		return result;
	};
	//直接还原出一个实例
	_con.getInstance = function(bina) {
		bina.__proto__ = _con.prototype;
		return bina;
	};
	_con.build = function(goods_id, bus_id) {
		return _con.findByGoodsId(goods_id, bus_id) || new _con(goods_id)
	};
	_con.findByGoodsId = function (goods_id, bus_id) {
		bus_id || (bus_id = GoodsCon.getAlone(goods_id).bus_id);
		return _con.get(db_id_prefix + goods_id + "|" + bus_id);
	},
	_con.equalGoods = function(bina_id, goods_id) {
		return bina_id.indexOf(db_id_prefix + goods_id + "|") === 0;
	};
	_con.equalBus = function(bina_id, bus_id) {
		return bina_id.substr(bina_id.indexOf("|")) === bus_id;
	};
	_con.getGoodsId = function(bina_id) {
		return bina_id.substr(0, bina_id.indexOf("|")).substr(db_id_prefix.length);
	};
	_con.getBusId = function(bina_id) {
		return bina_id.substr(bina_id.indexOf("|") + 1);
	};
	_con.findByBusId = function(bus_id) {
		return db.find_list(db_table_name, {
			bus_id: bus_id
		}).map(function(bina_info) {
			return _con.getInstance(bina_info)
		});
	};

	var db = require("../db/index");
	var config = require("../_include/config");
	var db_table_name = config.dbname.bina;
	var db_id_prefix = config.dbIdPrefix.bina;
	var BusCon = require("../bus/_con");
	var GoodsCon = require("../goods/_con");
	var helper = require("../_include/helper");
}());